import apply from '@/api/apply'
import { useApplyStore, useAuthStore } from '@/store'
import type { AcctInfo } from "@/types";

const { sessionid } = storeToRefs(useAuthStore())
const applyStore = useApplyStore()
const {
  mer_type,
  steps,
  currentStep,
  certInfo,
  merInfo,
  acctInfo,
  applyId,
  licenseInfo,
  operatorInfo,
  contactInfo,
  settlementInfo,
} = storeToRefs(applyStore)

export function useSteps(inputType: string) {
  // 在页面onShow里面更新步骤条状态
  onShow(() => {
    // 先判断当前页面应该在第几页
    const index = steps.value.indexOf(inputType)
    if (currentStep.value !== index) {
      currentStep.value = index
    }
  })
  // 页面的下一步方法
  async function next() {
    // 调用api提交
    if (mer_type.value === '3') {
      const object = Object.assign({
        sessionid: sessionid.value,
        applyId: applyId.value,
        pageNo: `${currentStep.value + 1}`,
      }, certInfo.value, merInfo.value)
      const { data } = await apply.saveStepSmallInfo(object)
      if (data.status === 'success') {
        await applyStore.setApplyInfo(data.data)
        currentStep.value += 1
        uni.navigateTo({
          url: `/pages-sub/apply/input-${steps.value[currentStep.value]}`,
        })
      }
    }
    else {
      const object = Object.assign({
        sessionid: sessionid.value,
        applyId: applyId.value,
        pageNo: `${currentStep.value + 1}`,
      }, {
        licenseInfo: Object.assign(licenseInfo.value, {
          merType: mer_type.value,
        }),
        operatorInfo: operatorInfo.value,
        contactInfo: contactInfo.value,
      })
      const { data } = await apply.saveStepInfo(object)
      if (data.status === 'success') {
        await applyStore.setApplyInfo(data.data)
        // 对经营者就是联系人的情况单独处理
        if (currentStep.value === 1) {
          if (operatorInfo.value.isSpecContact === '1') {
            steps.value = ['cert', 'operator', 'settlement']
          }
          else {
            steps.value = ['cert', 'operator', 'contact', 'settlement']
          }
        }
        currentStep.value += 1
        uni.navigateTo({
          url: `/pages-sub/apply/input-${steps.value[currentStep.value]}`,
        })
      }
    }
  }
  function redirect () {
    const pages = getCurrentPages()
    console.log(pages)
    let index = 0

    // 防止出现闪屏回退页面情况
    uni.redirectTo({
      url: `/pages-sub/apply/done`,
    });

    // 遍历页面栈
    // for (let page of pages) {
    //   if (/input-/.test(page.route)) {
    //     // 遍历到input页面，结束遍历，
    //     uni.navigateBack({
    //       delta: pages.length - index,
    //       success: () => {
    //         uni.navigateTo({
    //           url: '/pages-sub/apply/done',
    //         })
    //       }
    //     })
    //     break
    //   } else {
    //     index++
    //   }
    // }
  }

    function redirectBack() {
      const pages = getCurrentPages();
      console.log(pages);
      let index = 0;
      // 遍历页面栈
      for (let page of pages) {
        if (/input-/.test(page.route)) {
          // 遍历到input页面，结束遍历，
          uni.navigateBack({
            delta: pages.length - index,
            // success: () => {
            //   uni.navigateTo({
            //     url: '/pages-sub/apply/done',
            //   })
            // }
          })
          break
        } else {
          index++
        }
      }
    }

        function redirectBack_list() {
          const pages = getCurrentPages();
          console.log(pages);
          let index = 0;
          // 遍历页面栈
          for (let page of pages) {
            if (/input-/.test(page.route)) {
              // 遍历到input页面，结束遍历，
              uni.navigateBack({
                delta: pages.length - index,
                success: () => {
                  uni.navigateTo({
                    url: "/pages-sub/apply/list",
                  });
                }
              });
              break;
            } else {
              index++;
            }
          }
        }

  async function submit() {
    if (mer_type.value === '3') {
      const object = Object.assign({
        sessionid: sessionid.value,
        applyId: applyId.value,
        pageNo: `${currentStep.value + 1}`,
      }, certInfo.value, merInfo.value, acctInfo.value)
      const { data } = await apply.submitAllSmallInfo(object)
      if (data.status === 'success') {
        applyStore.resetApplyInfo()
        redirect()
      }else{
        const form = reactive<AcctInfo>({
          settleAcct: "",
          acctName: "",
          bankName: "",
          managerNo: "",
          managerName: "",
        });
        acctInfo.value = form;
      }
    }
    else {
      const object = Object.assign({
        sessionid: sessionid.value,
        applyId: applyId.value,
        pageNo: `${currentStep.value + 1}`,
      }, {
        licenseInfo: Object.assign(licenseInfo.value, {
          merType: mer_type.value,
        }),
        operatorInfo: operatorInfo.value,
        contactInfo: contactInfo.value,
        settlementInfo: settlementInfo.value,
      })
      const { data } = await apply.submitAllInfo(object)
      if (data.status === 'success') {
        applyStore.resetApplyInfo()
        redirect()
      }
    }
  }
  return { next, submit, redirectBack, redirectBack_list };
}
